# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : 16_queue_based_on_stacks.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2022/1/28 10:28
------------------------------------------
    用栈实现队列
    思路：用两个栈实现，一个作为入队栈，一个作为出队栈
"""


class StackQueue:
    def __init__(self):
        """
            这里用 Python的列表模拟栈
        """
        self.stack_in = []
        self.stack_out = []

    def en_queue(self, element):
        """入栈"""
        self.stack_in.append(element)

    def de_queue(self):
        """出栈"""
        if not self.stack_out:
            self.transfer()

        if not self.stack_out:
            # 正常的队列为空时，向队列获取数据时会阻塞，这里用异常替代
            raise Exception("队列为空")

        return self.stack_out.pop()

    def transfer(self):
        """
            将元素从 stack_in出栈，然后入栈到 stack_out
        """
        for _ in range(len(self.stack_in)):
            self.stack_out.append(self.stack_in.pop())


def demo():
    my_queue = StackQueue()
    for i in range(1, 4):
        my_queue.en_queue(i)

    print(my_queue.de_queue())
    my_queue.en_queue("A")

    for _ in range(3):
        print(my_queue.de_queue())


if __name__ == '__main__':
    demo()
